package info.techgeek.labs.java5Features.generics;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class GenericArrayList {

	public static void main(String[] args) {

		List<Integer> arrayList1 = new ArrayList<Integer>();
		arrayList1.add(1);
		arrayList1.add(2);
		arrayList1.add(4);
		arrayList1.add(7);
		
		List<Integer> arrayList2 = new ArrayList<Integer>();
		arrayList2.add(0);
		arrayList2.add(2);
		arrayList2.add(3);
		arrayList2.add(5);

		Set<List<Integer>> lists= new HashSet<List<Integer>>();
		lists.add(arrayList1);
		lists.add(arrayList2);
		
		List<Integer> arrayList3 = merge(lists);
		for(Integer integer : arrayList3 ){
			System.out.println(integer);
		}

	}

	public static <T extends Comparable<? super T>> List<T> merge(Set<List<T>> lists) {
		int totalSize = 0; // every element in the set
		for (List<T> l : lists) {
			totalSize += l.size();
		}

		List<T> result = new ArrayList<T>(totalSize);

		List<T> lowest;

		while (result.size() < totalSize) { // while we still have something to
											// add
			lowest = null;

			for (List<T> l : lists) {
				if (!l.isEmpty()) {
					if (lowest == null) {
						lowest = l;
					} else if (l.get(0).compareTo(lowest.get(0)) <= 0) {
						lowest = l;
					}
				}
			}
			result.add(lowest.get(0));
			lowest.remove(0);
		}
		return result;
	}
}
